package org.nocepko.android.sumc;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class DebugActivity extends Activity {
	
	private final static String TAG = "sumc.DEBUG";
	
	private final static int OPEN_REGULAR_ID = Menu.FIRST;
	private final static int DOWNLOAD_DEBUG_ID = OPEN_REGULAR_ID + 1; 

	private TextView mText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.debug);
		mText = (TextView) findViewById(R.id.text_debug);
	}

    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(0, OPEN_REGULAR_ID, 0, "прозта база");
    	menu.add(0, DOWNLOAD_DEBUG_ID, 0, "даунлоуд дебъг");
    	
    	return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case OPEN_REGULAR_ID:
			onOpenRegularSelected();
			return true;
		case DOWNLOAD_DEBUG_ID:
			onDownloadDebugSelected();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void onDownloadDebugSelected()
	{
		mText.setText("Download Debug...");
		
		HttpRequestBase method = null;
		HttpClient client = new DefaultHttpClient();
		
		try {
			method = new HttpGet("http://gps.skgt-bg.com/Web/SelectByLine.aspx");
			HttpResponse response = client.execute(method);
			InputStream is = response.getEntity().getContent();
			Header hEncoding = response.getEntity().getContentEncoding();
			if (hEncoding != null) {
				mText.append("\nEncoding: " + hEncoding.getValue());
			}
			Xml.parse(is, Xml.Encoding.UTF_8, new DefaultHandler() {

				@Override
				public void endElement(String uri, String localName, String name)
						throws SAXException {
					mText.append("\nuri: " + uri);
					mText.append("\nlocalName: " + localName);
					mText.append("\nname: " + name);
				}

				@Override
				public void error(SAXParseException e) throws SAXException {
					mText.append("\nERR: " + e.getMessage());
				}

				@Override
				public void startDocument() throws SAXException {
					// TODO Auto-generated method stub
					super.startDocument();
				}

				@Override
				public void startElement(String uri, String localName,
						String name, Attributes attributes) throws SAXException {
					// TODO Auto-generated method stub
					super.startElement(uri, localName, name, attributes);
				}
			});
			Log.i(TAG, "seems like parsing is successful!");
		} catch (IllegalArgumentException e) {
			Log.w(TAG, "Looks like an invalid url that thing ...");
		} catch (ClientProtocolException e) {
			Log.e(TAG, e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, e.getMessage());
		} catch (SAXException e) {
			Log.e(TAG, e.getMessage());
		} finally {
			if (method != null) {
				method.abort();
			}
			client.getConnectionManager().shutdown();
		}
		
	}
	
	protected void onOpenRegularSelected() {
        String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();
        Log.i(TAG, "storagePath: " + storagePath);
        String dbFilePath = storagePath + "/sumc.db";
        Log.i(TAG, "dbFilePath: " + dbFilePath);
        
        File dbFile = new File(dbFilePath);
        SQLiteDatabase db = null;
        try {
        	db = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
            if (db.isOpen()) {
            	Toast.makeText(this, "database is fucking open!", Toast.LENGTH_LONG).show();
            }
            mText.append("\nOpened the database!");
            db.close();
        } catch (SQLiteException e) {
        	Toast.makeText(this, "db made a boo boo", 2);
        }

        Log.i(TAG, "db.isOpen? " + ((db != null) && db.isOpen()) ) ;
        
	}
}
